var wxCharts = require('../../utils/wxcharts.js');
var app = getApp();
var lineChart = null;
var startPos = null;
const moment = require('../../utils/moment.js');
Page({
    data: {
      hiddenmodalput: true,
      inputWeight: null
    //可以通过hidden是否掩藏弹出框的属性，来指定那个弹出框
    },
  //点击按钮痰喘指定的hiddenmodalput弹出框  
  modalinput: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  //取消按钮  
  cancel: function () {
    this.setData({
      hiddenmodalput: true
    });
  },
  //确认  
  confirm: function () {
    if (this.data.inputWeight) {
      this.setData({
        hiddenmodalput: true
      })
      // 在这里把数据保存到微信缓存
      console.log(this.data.inputWeight)
      this.saveCurrentWeight(this.data.inputWeight).then(this.reflashData)
    } else {
      wx.showModal({
        title: '提示',
        content: '请输入体重！',
        showCancel: false,
        confirmText: '确定'
      })
    }
  },
  saveCurrentWeight (weight) {
    let today = moment().format('YYYY-MM-DD')
    return app.apis().addWeightLog(app.globalData.userObject.id, today, weight)
  },
  bindinputWeight (e) {
    this.setData({
      inputWeight: e.detail.value
    });
  },
  touchHandler: function (e) {
    lineChart.scrollStart(e);
  },
  moveHandler: function (e) {
    lineChart.scroll(e);
  },
  touchEndHandler: function (e) {
    lineChart.scrollEnd(e);
    lineChart.showToolTip(e, {
        format: function (item, category) {
            return category + ' ' + item.name + ':' + item.data 
        }
    });        
  },
  createSimulationData: function (weightLogs) {
    var categories = [];
    var data = [];
    weightLogs.forEach(item => {
      categories.push(item.date);
      data.push(parseFloat(item.weight));
    })
    return {
      categories: categories,
      data: data
    }
  },
  makeChart(simulationData) {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }

    lineChart = new wxCharts({
      canvasId: 'lineCanvas',
      type: 'line',
      categories: simulationData.categories,
      animation: false,
      series: [{
        name: '体重',
        data: simulationData.data,
        format: function (val, name) {
          return val.toFixed(2) + 'KG';
        }
      }],
      xAxis: {
        disableGrid: false
      },
      yAxis: {
        title: '体重 (KG)',
        format: function (val) {
          return val.toFixed(2);
        },
        min: 35,
        max: 60
      },
      width: windowWidth,
      height: 200,
      dataLabel: true,
      dataPointShape: true,
      enableScroll: true,
      extra: {
        lineStyle: 'curve'
      }
    });
  },
  onShow (e) {
    this.reflashData()
  },
  reflashData () {
    app.apis().getWeightLogs(app.globalData.userObject.id).then(data => {
      this.makeChart(this.createSimulationData(data._embedded.weight_logs))
    })
  }
});